<template>
  <div>
    <!-- 商品推荐（广告） -->
    <Advertis
      v-if="$route.name !== 'search'"
      class="avt"
      :advertis="advertisList"
    />

    <template v-if="$route.name !== 'search'">
      <!-- 为你推荐 -->
      <ProductList :products="products" />
      <!-- 正在加载动画 -->
      <div class="load">
        <Load
          v-if="
            maxCount > products.length &&
            status === 0 &&
            this.products.length < this.pager.count
          "
        />
      </div>
    </template>
    <template v-else>
      <!-- 搜索商品列表 -->
      <ProductList :products="searchProducts" />
      <!-- 正在加载动画 -->
      <div class="load">
        <Load v-if="pager.count !== searchProducts.length && status === 0" />
      </div>
      <div class="end" v-if="pager.count <= searchProducts.length">
        <img :src="require('@/assets/end.png')" alt="" />
      </div>
    </template>
  </div>
</template>
<style lang="scss" scoped>
.avt {
  margin-bottom: 20px;
}
.load {
  position: relative;
  display: flex;
  height: 100px;
  margin-top: 30px;
}
.end {
  // margin: auto;
  margin-top: 50px;
  display: flex;
  justify-content: center;
}
</style>

<script>
import Advertis from './advertis'
import ProductList from './productList'
import Load from '../../components/Loading'
import { getCommodity } from '../../api/commodity'
import { url } from '../../utils/request'
export default {
  components: {
    Advertis,
    ProductList,
    Load
  },
  data () {
    return {
      // 广告推荐
      advertisList: [],
      products: [], // 为你推荐商品列表
      searchProducts: [], // 搜索商品列表
      status: 1, // 请求数据状态，1表示没有任何请求，0表示请求中
      maxCount: 15 * 5, // 为你推荐最多展示数量
      pager: {
        pageIndex: 1,
        pageSize: 15,
        count: 100,
        keyWord: ''
      }
    }
  },
  mounted () {
    // console.log(value)
    // this.products =

    // 搜索获取商品列表
    if (this.$route.name === 'search') {
      this.pager.pageIndex = 1
      this.pager.pageSize = 15
      this.pager.keyWord = this.$route.query.q

      this.initProducts(this.pager)
      this.$route.query.count = this.pager.count
    } else {
      // 获取首页商品列表
      this.advertisList = this.initAdvertis()

      // 为你推荐
      this.initProducts(this.pager)
    }

    this.$nextTick(function () {
      window.addEventListener('scroll', this.onScroll, false)
    })
  },
  watch: {
    $route (route) {
      if (route.name === 'search') {
        console.log('变化了')
        this.pager.pageIndex = 1
        this.pager.pageSize = 15
        this.pager.keyWord = this.$route.query.q
        this.searchProducts = []
        this.initProducts(this.pager)
        this.$route.query.count = this.pager.count
      }
    }
  },
  methods: {
    // 初始化8大商品推荐
    initAdvertis () {
      const arr = []
      for (let index = 0; index < 8; index++) {
        if (index === 0) {
          arr.push({
            id: index + 1,
            imgurl:
              'https://img12.360buyimg.com/babel/s290x370_jfs/t1/162556/15/9172/203599/603ef7a1E153bf600/2cb4c8faa9ce7415.jpg!cc_290x400.webp'
          })
        } else if (index === 1) {
          arr.push({
            id: index + 1,
            imgurl:
              'https://img10.360buyimg.com/babel/s290x370_jfs/t1/133621/19/17467/111378/5fbf8318E6ccf4818/c5e52bf95e7c3850.jpg!cc_290x400.webp'
          })
        } else {
          if (index % 2 === 0) {
            arr.push({
              id: index + 1,
              imgurl:
                'https://gw.alicdn.com/imgextra/i4/O1CN01smy7dx1Mmy5Cm6IAn_!!6000000001478-0-tps-468-602.jpg'
            })
          } else {
            arr.push({
              id: index + 1,
              imgurl:
                'https://gw.alicdn.com/imgextra/i1/O1CN01UmjOir1qwWp6gNB3D_!!6000000005560-0-tps-468-602.jpg'
            })
          }
        }
      }
      return arr
    },
    // 初始化商品列表
    async initProducts (pager) {
      if (this.$route.name !== 'search') {
        pager.keyWord = ''
      }

      const arr = []
      const res = await getCommodity(pager)
      console.log(res)
      res.data.data.data.forEach((item) => {
        arr.push({
          id: item.id,
          productName: item.productName,
          price: item.price,
          productImgurl: `${url}/uploadfiles/${
            item.coverPicture.split(' ')[0]
          }`
        })
      })

      this.pager.count = res.data.data.pager.rowsTotal
      this.pager.pageIndex++
      this.status = 1

      if (this.$route.name === 'search') {
        this.searchProducts = this.searchProducts.concat(arr)
      } else {
        this.products = this.products.concat(arr)
      }

      // return arr
    },
    // 获取滚动条当前的位置
    getScrollTop () {
      var scrollTop = 0
      if (document.documentElement && document.documentElement.scrollTop) {
        scrollTop = document.documentElement.scrollTop
      } else if (document.body) {
        scrollTop = document.body.scrollTop
      }
      return scrollTop
    },
    // 获取当前可视范围的高度
    getClientHeight () {
      var clientHeight = 0
      if (document.body.clientHeight && document.documentElement.clientHeight) {
        clientHeight = Math.min(
          document.body.clientHeight,
          document.documentElement.clientHeight
        )
      } else {
        clientHeight = Math.max(
          document.body.clientHeight,
          document.documentElement.clientHeight
        )
      }
      return clientHeight
    },

    // 获取文档完整的高度
    getScrollHeight () {
      return Math.max(
        document.body.scrollHeight,
        document.documentElement.scrollHeight
      )
    },
    // 滚动事件触发下拉加载
    onScroll () {
      // if ($route.name !== "search") {
      // 获取首页为你推荐商品
      // console.log(this.getScrollHeight() - this.getClientHeight() - this.getScrollTop())
      if (
        this.getScrollHeight() - this.getClientHeight() - this.getScrollTop() <=
        700
      ) {
        if (this.$route.name !== 'search') {
          if (
            this.status === 1 &&
            this.products.length < this.maxCount &&
            this.products.length < this.pager.count
          ) {
            this.status = 0
            // 页码，分页用，默认第一页
            console.log('开始')
            this.status = 0

            this.initProducts(this.pager)

            // setTimeout(() => {
            //   this.status = 1
            //   this.products = this.products.concat(
            //     this.initProducts(this.products.length)
            //   )
            //   console.log('ok')
            // }, 500)
          }
        } else {
          if (
            this.status === 1 &&
            this.searchProducts.length < this.pager.count
          ) {
            this.status = 0
            // setTimeout(() => {

            this.initProducts(this.pager)
            // this.searchProducts = this.searchProducts.concat(
            //   this.initProducts(this.searchProducts.length)
            // )
            // console.log('ok')
            // }, 500)
          }
        }
      }
      // } else {
      //   // 获取搜索商品列表

      // }
    }
  },
  beforeDestroy () {
    window.removeEventListener('scroll', this.onScroll, false)
  }
}
</script>

<style>
</style>
